package com.orange.fastdfs.controller;

import com.orange.fastdfs.modle.FileSystem;
import com.orange.fastdfs.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
@RestController
@RequestMapping("/files")
public class FileController {

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        //将文件先存储在web服务器上(本机),在调用fastDFS的client将文件上传到 fastDFS服务器
        FileSystem fileSystem = new FileSystem();

        String contentType = file.getContentType();
        log.info("上传的文件类型为：{}", contentType);

        byte[] file_buff = null;
        //把文件转成输入流
        InputStream inputStream = file.getInputStream();
        if (inputStream != null) {
            //获取输入流中可读取的数据大小
            int len = inputStream.available();
            //创建足够大的缓冲区
            file_buff = new byte[len];
            //一次性把输入流中的数据全都读入到缓冲区file_buff,那file_buff就要足够大,占用内存也会很大
            inputStream.read(file_buff);
        }
        //关闭输入流
        inputStream.close();

        //文件原始名称
        String originalFilename = file.getOriginalFilename();

        //文件扩展名比如22.jpg
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("文件扩展名后缀 = {}", extension);//.jpg
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        log.info("文件类型 = {}", filenameExtension);//jpg
        if (filenameExtension == null) {
            return Result.error("此文件没有文件扩展名");
        }

        //通过fastDSF的client代码访问tracker和storage
        try {
            //加载fastDFS客户端的配置 文件
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            System.out.println("network_timeout=" + ClientGlobal.g_network_timeout + "ms");
            System.out.println("charset=" + ClientGlobal.g_charset);

            //创建tracker的客户端
            TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
            //通过TrackerClient对象获取TrackerServer信息
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            StorageServer storageServer = null;

            //定义storage的客户端,建立与Storage服务器的连接
            StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

            //文件元信息
            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("fileName", "52.png");

            //执行上传
            String fileId = storageClient.upload_file1(file_buff, filenameExtension, metaList);
            System.out.println("upload success. file id is: " + fileId);
            fileSystem.setFileId(fileId);
            fileSystem.setFilePath(fileId);
            fileSystem.setFileName(originalFilename);
            fileSystem.setFileSize(file.getSize());
            fileSystem.setFileType(contentType);
            //通过调用service及dao将文件的路径存储到数据库中

            //关闭storage客户端
            storageClient.close();
        } catch (Exception e) {
            log.error("上传文件失败：", e);
            e.printStackTrace();
        }

        return Result.success(fileSystem);
    }
}
